<template>
  <div class="station-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">站点管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" size="large" @click="handleAdd">
          添加站点
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="站点名称" label-width="80px">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入站点名称"
            clearable
            size="default"
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            size="default"
            style="width: 120px"
          >
            <el-option label="正常" value="active" />
            <el-option label="繁忙" value="busy" />
            <el-option label="关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" size="default" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" size="default" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 站点列表 -->
    <el-card class="table-card" shadow="never">

      <el-table 
        :data="stationList" 
        v-loading="loading"
        stripe
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="name" label="站点名称" width="180" show-overflow-tooltip>
          <template #default="scope">
            <span class="table-text">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="250" show-overflow-tooltip>
          <template #default="scope">
            <span class="table-text">{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="140">
          <template #default="scope">
            <span class="table-text">{{ scope.row.contactPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="managerName" label="站长" width="110" align="center">
          <template #default="scope">
            <span v-if="scope.row.managerName" class="table-text">{{ scope.row.managerName }}</span>
            <el-tag v-else type="info" size="default">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="managerPhone" label="站长电话" width="130" align="center">
          <template #default="scope">
            <span v-if="scope.row.managerPhone" class="table-text">{{ scope.row.managerPhone }}</span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容量" width="110" align="center">
          <template #default="scope">
            <span class="table-text">{{ scope.row.capacity }}kg</span>
          </template>
        </el-table-column>
        <el-table-column prop="currentLoad" label="当前负载" width="140" align="center">
          <template #default="scope">
            <div class="load-info">
              <span class="table-text">{{ scope.row.currentLoad }}kg</span>
              <el-progress 
                :percentage="(scope.row.currentLoad / scope.row.capacity * 100)" 
                :stroke-width="6"
                :show-text="false"
                :color="getLoadColor(scope.row.currentLoad / scope.row.capacity)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="default">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                link
                size="default" 
                :icon="Edit"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-select
                :model-value="scope.row.status"
                size="small"
                style="width: 90px"
                @change="(value) => handleStatusChange(scope.row, value)"
              >
                <el-option label="正常" value="active" />
                <el-option label="繁忙" value="busy" />
                <el-option label="关闭" value="closed" />
              </el-select>
              <el-button 
                type="danger" 
                link
                size="default" 
                :icon="Delete"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑站点对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="stationForm" 
        :rules="stationRules" 
        ref="stationFormRef"
        label-width="100px"
      >
        <el-form-item label="站点名称" prop="name">
          <el-input v-model="stationForm.name" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="站点地址" prop="address">
          <el-input v-model="stationForm.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input 
            v-model="stationForm.contactPhone" 
            placeholder="请输入座机电话，如：010-12345678"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="地理坐标">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item prop="latitude">
                <el-input 
                  v-model.number="stationForm.latitude" 
                  placeholder="纬度"
                  type="number"
                  step="0.000001"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="longitude">
                <el-input 
                  v-model.number="stationForm.longitude" 
                  placeholder="经度"
                  type="number"
                  step="0.000001"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="站点容量" prop="capacity">
          <el-input-number 
            v-model="stationForm.capacity" 
            :min="100" 
            :max="10000" 
            :step="100"
            placeholder="请输入站点容量(kg)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分配管理员" prop="managerId">
          <el-select 
            v-model="stationForm.managerId" 
            placeholder="请选择管理员"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option 
              v-for="manager in availableManagers" 
              :key="manager.id"
              :label="manager.realName" 
              :value="manager.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { stationsAPI, usersAPI } from '@/api'

// 组件名称
defineOptions({
  name: 'StationManagement'
})

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const stationList = ref([])
const availableManagers = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: null
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentStation = ref(null)

// 表单数据
const stationForm = reactive({
  name: '',
  address: '',
  contactPhone: '',
  latitude: null,
  longitude: null,
  capacity: 1000,
  managerId: null
})

// 表单引用
const stationFormRef = ref()

// 表单验证规则
const stationRules = {
  name: [
    { required: true, message: '请输入站点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '站点名称长度应为2-50个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入站点地址', trigger: 'blur' },
    { min: 5, max: 200, message: '地址长度应为5-200个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^0\d{2,3}-?\d{7,8}$/, message: '请输入有效的座机号码，如：010-12345678', trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度范围应在-90到90之间', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { type: 'number', min: -180, max: 180, message: '经度范围应在-180到180之间', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入站点容量', trigger: 'blur' },
    { type: 'number', min: 100, max: 10000, message: '容量范围应在100-10000kg之间', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑站点' : '添加站点'
})

// 获取站点列表
const fetchStations = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const response = await stationsAPI.getStations(params)
    stationList.value = response.list || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败')
  } finally {
    loading.value = false
  }
}

// 获取管理员列表
const fetchManagers = async () => {
  try {
    const response = await usersAPI.getUsers({ 
      page: 1, 
      pageSize: 1000, 
      role: 'station_manager' 
    })
    availableManagers.value = response.list || []
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
  }
}

// 状态相关函数
const getStatusType = (status) => {
  const types = {
    active: 'success',
    busy: 'warning', 
    closed: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    active: '正常',
    busy: '繁忙',
    closed: '关闭'
  }
  return texts[status] || '未知'
}

const getLoadColor = (ratio) => {
  if (ratio < 0.6) return '#67C23A'
  if (ratio < 0.8) return '#E6A23C'
  return '#F56C6C'
}

// 事件处理函数
const handleSearch = () => {
  pagination.page = 1
  fetchStations()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: null
  })
  handleSearch()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  currentStation.value = row
  Object.assign(stationForm, {
    name: row.name,
    address: row.address,
    contactPhone: row.contactPhone,
    latitude: row.latitude,
    longitude: row.longitude,
    capacity: row.capacity,
    managerId: row.managerId || ''
  })
  dialogVisible.value = true
}


const handleStatusChange = async (row, newStatus) => {
  const oldStatus = row.status
  
  // 如果状态没有改变，不做处理
  if (oldStatus === newStatus) {
    return
  }
  
  const statusText = {
    active: '正常',
    busy: '繁忙',
    closed: '关闭'
  }
  
  try {
    // 先更新UI（乐观更新）
    row.status = newStatus
    
    // 调用API更新后端
    await stationsAPI.updateStationStatus(row.id, newStatus)
    ElMessage.success(`状态已更改为：${statusText[newStatus]}`)
    
    // API成功后重新获取数据以确保同步
    await fetchStations()
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    
    // API失败时恢复原状态
    row.status = oldStatus
    
    // 强制重新获取数据
    await fetchStations()
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除站点 "${row.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await stationsAPI.deleteStation(row.id)
    ElMessage.success('删除成功')
    fetchStations()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!stationFormRef.value) return
  
  try {
    await stationFormRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await stationsAPI.updateStation(currentStation.value.id, stationForm)
      ElMessage.success('更新成功')
    } else {
      await stationsAPI.createStation(stationForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchStations()
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      console.error('提交失败:', error)
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchStations()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchStations()
}

const resetForm = () => {
  Object.assign(stationForm, {
    name: '',
    address: '',
    contactPhone: '',
    latitude: null,
    longitude: null,
    capacity: 1000,
    managerId: null
  })
  stationFormRef.value?.resetFields()
}

// 生命周期
onMounted(() => {
  fetchStations()
  fetchManagers()
})
</script>

<style scoped>
.station-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.filter-card {
  margin-bottom: 12px;
  border-radius: 8px;
}

:deep(.filter-card .el-card__body) {
  padding: 16px 20px;
}

.search-form {
  margin-bottom: 0;
}

:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 16px;
}

:deep(.search-form .el-form-item__label) {
  font-size: 15px;
  color: #606266;
  font-weight: 500;
}

:deep(.search-form .el-input__inner) {
  font-size: 15px;
}

:deep(.search-form .el-button) {
  font-size: 15px;
  padding: 9px 18px;
}

.table-card {
  border-radius: 8px;
}

:deep(.table-card .el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  font-size: 15px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  font-size: 15px;
  padding: 14px 0;
}

:deep(.el-table td.el-table__cell) {
  padding: 14px 0;
}

.table-text {
  font-size: 15px;
  color: #303133;
}

.text-placeholder {
  font-size: 15px;
  color: #909399;
}

.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.action-buttons :deep(.el-select) {
  margin: 0 4px;
}

.action-buttons :deep(.el-select .el-input__wrapper) {
  font-size: 14px;
}

:deep(.el-table .el-button) {
  font-size: 15px;
  padding: 6px 10px;
  margin: 0;
}

:deep(.el-table .el-tag) {
  font-size: 14px;
  padding: 4px 10px;
}

.load-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.load-info span {
  font-size: 14px;
  color: #303133;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 16px 20px;
}

:deep(.el-pagination) {
  font-size: 15px;
}

:deep(.el-pagination .el-pager li) {
  font-size: 15px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.station-detail {
  padding: 16px 0;
}
</style>

